﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.User;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Write.Application.Handler.User
{
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IMapper _mapper;

        public CreateRoleHandler(IBaseRepository<RoleModel> roleRepository, IMapper mapper)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 添加角色信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            //角色名称唯一校验
            var role = _roleRepository.GetAll().FirstOrDefault(p => p.RoleName == request.RoleName && p.IsDelete==false);
            if (role != null)
            {
                result.Code = StatusEnum.Fail;
                result.Message = "角色名称重复";
                return Task.FromResult(result);
            }
            var model =_mapper.Map<RoleModel>(request);
            model.CreateTime = DateTime.Now;
            model.Creater = "张三";
            model.UpdateTime = null;
            var res =_roleRepository.Add(model);
            if (res > 0)
            {
                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "添加成功";
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加失败";
            }
            return Task.FromResult(result);

        }
    }
}
